import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_form_field.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:quiver/strings.dart';

// class DateTimeSelect extends CryFormField {
class DateTimeSelect extends CryFormField {
  DateTimeSelect(
      BuildContext context, {
        Key? key,
        String? value,
        String? label,
        double? width,
        double? padding,
        ValueChanged? onChange,
        FormFieldSetter? onSaved,
        FormFieldSetter? onDateChange,
        DateTime? firstDate,
        DateTime? lastDate,
      }) : super(
    key: key,
    width: width,
    padding: padding,
    builder: (CryFormFieldState state) {
      return TextFormField(
        readOnly: true,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(horizontal: 10),
          labelText: label,
        ),
        controller: TextEditingController(text: value),
        onChanged: (v) {
          if (onChange != null) {
            onChange(v);
          }
        },
        onTap: () async {
          DateTime valueDt = isBlank(value) ? DateTime.now() : DateTime.parse(value!);
          final DateTime? picked = await showDatePicker(
            context: context,
            initialDate: valueDt,
            firstDate: firstDate!=null?firstDate:DateTime(1900, 1),
            lastDate: lastDate!=null?lastDate: DateTime(2031, 12),
          );
          if(picked != null){
            TimeOfDay selectedTime = TimeOfDay(hour: valueDt.hour, minute: valueDt.minute);
            final TimeOfDay? time = await showTimePicker(
                context: context,
                initialTime: selectedTime,
                initialEntryMode: TimePickerEntryMode.input
            );
            DateTime dataTime = new DateTime(picked.year,picked.month,picked.day,time!.hour,time.minute);
            if (dataTime != null) {
              value = formatDate(dataTime, [yyyy, '-', mm, '-', dd,' ',HH,':',nn,":",ss]);
            }
            if (onDateChange != null) {
              onDateChange(value);
            }
            state.didChange();
          }
        },
        onSaved: onSaved,
      );
    },
  );
}